package com.hjm.strategy.kdb;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * KDB 请求统一封装工具
 */

@Slf4j
public class KdbRequestHelper {

    private static final RSAHelper rsaHelper = new RSAHelper();

    static {
        try {
            rsaHelper.initKey(KdbConfig.PRIVATE_KEY, KdbConfig.PUBLIC_KEY, 1024);
        } catch (Exception e) {
            throw new RuntimeException("初始化RSA失败", e);
        }
    }

    /**
     * 发送请求（加密 + 签名）
     */
    public static String send(String url, String bizType, String bodyJson) throws Exception {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("bizType", bizType);
        requestMap.put("nonceStr", RandomCodeUtil.buildRandomNum(32));
        requestMap.put("agentCode", KdbConfig.AGENT_CODE);
        requestMap.put("version", KdbConfig.VERSION);
        requestMap.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        log.info("请求参数:{}", JSON.toJSONString(requestMap));
        // 加密 body
        String encryptedBody = new String(
                rsaHelper.encryptRSA(bodyJson.getBytes(StandardCharsets.UTF_8), true, "UTF-8"),
                StandardCharsets.UTF_8
        );
        requestMap.put("body", encryptedBody);

        // 签名
        String plainText = KdbSignUtil.getPlainText(requestMap);
        String sign = new String(
                rsaHelper.signRSA(plainText.getBytes(StandardCharsets.UTF_8), true, "UTF-8"),
                StandardCharsets.UTF_8
        );
        requestMap.put("sign", sign);
        String response = HttpUtil.post(url, JSON.toJSONString(requestMap));
        log.info("返回值:{}", response);
        return response;
    }
}
